package com.seuic.hnapps.project;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.seuic.hnapps.BaseActivity;
import com.seuic.hnapps.R;
import com.seuic.hnapps.bean.Sign_in_Bean;
import com.seuic.hnapps.posdsdk.pos_func.PosFuncs;
import com.seuic.hnapps.util.CommAdapter;
import com.seuic.hnapps.util.Constants;
import com.seuic.hnapps.util.DateUtil;
import com.seuic.hnapps.util.RTKInterface;
import com.seuic.hnapps.util.RWKInterface;
import com.seuic.hnapps.util.SFTPUtils;
import com.seuic.hnapps.util.ServiceCommon;
import com.seuic.hnapps.util.Sign_in_Callback;
import com.seuic.hnapps.util.SpUtils;
import com.seuic.hnapps.util.UpdateAppHttpUtil;
import com.solab.enc.DES3;
import com.solab.enc.HexT;
import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.MessageFactory;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.listener.ExceptionHandler;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 登录
 * 2019年7月31日17:45:52
 * isjingkai
 */

public class LogingActivity extends BaseActivity {

    private PosFuncs posFuncs;
    private String mUpdateUrl = "";

    @BindView(R.id.base_back_btn)
    LinearLayout baseBackBtn;
    @BindView(R.id.base_title_text)
    TextView baseTitleText;
    @BindView(R.id.loging_versions)
    TextView logingVersions;
    @BindView(R.id.loging_sbwh)
    ImageView logingSbwh;
    @BindView(R.id.loging_qd)
    ImageView logingQd;
    @BindView(R.id.loging_manage)
    ImageView logingManage;
    @BindView(R.id.loging_home_layout)
    LinearLayout logingHomeLayout;
    @BindView(R.id.input_accnum_edtext)
    EditText inputAccnumEdtext;
    @BindView(R.id.input_accnum_gztext)
    Button inputAccnumGztext;
    @BindView(R.id.input_accnum_oktext)
    Button inputAccnumOktext;
    @BindView(R.id.re_input_namelayout)
    LinearLayout reInputNamelayout;
    @BindView(R.id.input_accnum_layout)
    LinearLayout inputAccnumLayout;
    @BindView(R.id.input_password_edtext)
    EditText inputPasswordEdtext;
    @BindView(R.id.input_password_gztext)
    Button inputPasswordGztext;
    @BindView(R.id.input_password_oktext)
    Button inputPasswordOktext;
    @BindView(R.id.re_password_namelayout)
    LinearLayout rePasswordNamelayout;
    @BindView(R.id.input_password_layout)
    LinearLayout inputPasswordLayout;
    @BindView(R.id.singin_layout)
    LinearLayout singinLayout;
    private int num;
    long timer_time;
    private boolean is_work = false;
    private Timer mTimer2;
    private TimerTask mTask2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loging);
        ButterKnife.bind(this);
        this.setBackBtClick(R.id.base_back_btn);
        baseBackBtn.setVisibility(View.GONE);
        this.setTitleText(R.id.base_title_text, "(   " + "登陆" + "   )");
        logingSbwh.setVisibility(View.GONE);
        logingManage.setVisibility(View.GONE);
        isNetworkConnected(getApplicationContext());
        posFuncs = PosFuncs.getInstace();
        posFuncs.init(getApplicationContext());
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String version = packageInfo.versionName;
            logingVersions.setText("（版本:" + version + "）");
//            mUpdateUrl = "http://huinong.3todo.com/API/index/index.html?version=" + version; //模拟
//            mUpdateUrl = "http://190.190.15.79/api/index/index.html?version=" + version; //测试
            mUpdateUrl = "http://172.32.25.235/api/index/index.html?version=" + version;//正式
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //一进来先进行更新APP操作
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //更新地址
                .setUpdateUrl(mUpdateUrl)
                .handleException(new ExceptionHandler() {
                    @Override
                    public void onException(Exception e) {
                        e.printStackTrace();
                    }
                })
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .build()
                .update();

    }

    public void isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {

            } else {
                Toast.makeText(context, "网络连接异常，请检查您的网络连接", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @OnClick({R.id.loging_sbwh, R.id.loging_qd, R.id.loging_manage,
            R.id.input_accnum_gztext, R.id.input_accnum_oktext,
            R.id.input_password_gztext, R.id.input_password_oktext})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.loging_sbwh:
                //设备维护
                Toast.makeText(this, "该功能尚未开放~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.loging_qd:
                //设备签到
                logingHomeLayout.setVisibility(View.GONE);
                inputAccnumLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.loging_manage:
                //系统管理员
                Toast.makeText(this, "该功能尚未开放~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.input_accnum_gztext:
                //输入账号更正
                inputAccnumEdtext.setText("");
                break;
            case R.id.input_accnum_oktext:
                //输入账号确定
                if (inputAccnumEdtext.getText().toString().equals("")) {
                    Toast.makeText(this, "请输入账户", Toast.LENGTH_SHORT).show();
                } else {
                    SpUtils.getSPUtil(getApplicationContext()).putString("make_user", inputAccnumEdtext.getText().toString());
                    inputAccnumLayout.setVisibility(View.GONE);
                    inputPasswordLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.input_password_gztext:
                //输入密码更正
                inputPasswordEdtext.setText("");
                break;
            case R.id.input_password_oktext:
                //输入密码确定
                if (inputPasswordEdtext.getText().toString().equals("")) {
                    Toast.makeText(this, "请输入账户密码", Toast.LENGTH_SHORT).show();
                } else {
                    inputPasswordLayout.setVisibility(View.GONE);
                    singinLayout.setVisibility(View.VISIBLE);

                    mTimer2 = new Timer();
                    mTask2 = new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    timer_time = timer_time + 1000;
                                }
                            });
                        }
                    };
                    mTimer2.schedule(mTask2, 0, 1000);


                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            signin();
                        }
                    }).start();

                }
                break;
        }
    }


    private void signin() {
//        String Url = "http://190.190.15.79/api/index/sign_in";//测试
        String Url = "http://172.32.25.235/api/index/sign_in";//正式
//        String Url = "http://huinong.3todo.com/api/index/sign_in";//模拟
        //获取终端序列号
        String TermSerial = posFuncs.getTermSerial();
        Constants.X_NUM = posFuncs.getTermSerial();
        OkHttpUtils
                .post()
                .url(Url)
                .addParam("sn", TermSerial)
                .addParam("user_no", inputAccnumEdtext.getText().toString())
                .addParam("user_pwd", inputPasswordEdtext.getText().toString())
                .build()
                .execute(new Sign_in_Callback() {
                    @Override
                    public Sign_in_Bean parseNetworkResponse(Response response, int id) throws Exception {
                        return super.parseNetworkResponse(response, id);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e, int id) {
                        super.onError(call, response, e, id);
                        Logger.e(String.valueOf(e));
                        Toast.makeText(LogingActivity.this, "网络连接异常，请检查您的网络！", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(final Sign_in_Bean response, int id) {
                        super.onResponse(response, id);
                        if (response.getCode() == 1) {

                            //存储网点设备号
                            Logger.e("存储网点设备号" + response.getData().getDev_no());
                            SpUtils
                                    .getSPUtil(getApplicationContext())
                                    .putString("dev_no", response.getData().getDev_no());

                            //存储备付金账号
                            Logger.e("存储备付金账号" + response.getData().getUser_card_no());
                            SpUtils
                                    .getSPUtil(getApplicationContext())
                                    .putString("user_card_no", response.getData().getUser_card_no());
                            Constants.YANTAI_TERMNO = response.getData().getDev_no();
                            Constants.DEMO_F102 = response.getData().getUser_card_no();
                            //获取到网点设备号和备付金账号之后 进行和银行通信 获取主密钥和其他三个签到秘钥
                            new Thread(new Runnable() {
                                @Override
                                public void run() {

                                    try {
                                        num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 0);
                                        excuteMain(String.valueOf(num));
                                        SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);

                                        num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 0);
                                        excute(String.valueOf(num));
                                        Logger.e(timer_time + "");

                                        SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);

                                        Thread.sleep(3000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    inputAccnumEdtext.setText("");
                                    inputPasswordEdtext.setText("");
                                    singinLayout.setVisibility(View.GONE);
                                    inputAccnumLayout.setVisibility(View.VISIBLE);
                                    Toast.makeText(LogingActivity.this, response.getMsg() + ",请重新操作", Toast.LENGTH_SHORT).show();
                                    Logger.e(response.getMsg());
                                }
                            });
                        }

                    }
                });
    }

    /**
     * 签到 获取秘钥
     *
     * @param transn
     */
    public void excute(String transn) {

        IsoMessage msg = null;
        RWKInterface inter = new RWKInterface();

        msg = inter.packRequest(transn, posFuncs.getTermSerial());
        byte[] data = msg.writeData();
        // 重写报文头第7域长度值
        int hlen = Constants.ATMP_HEADER_LENGTH;
        int bodylen = data.length - hlen;
        String headF7 = ServiceCommon.appendZero(bodylen, 4);
        System.arraycopy(headF7.getBytes(), 0, data, 28, 4);
        // 生成MAC
        if (msg.getField(128) != null) {
            int start = hlen;
            int length = data.length - start - 8;
            byte[] inmac = new byte[length];
            byte[] outmac = new byte[16];
            System.arraycopy(data, start, inmac, 0, length);
            Logger.e("MAC数据=[{}]" + HexT.byteArr2HexStr(inmac));
            String mackey = Constants.YANTAI_MACKEY;
            // MAC99算法mak只需要16字节密钥
            if (mackey.length() > 16) {
                mackey = mackey.substring(0, 16);
            }
            DES3.getMacBlock_99(inmac, mackey.getBytes(), outmac);
            System.arraycopy(outmac, 0, data, data.length - 8, 8);
            Logger.e("请求MAC=[{}]" + new String(outmac).substring(0, 8));
        }
        byte[] send = null;
        // 报文加密，公网传输时，业务交易必须报文加密
        String encflag = msg.getHeadStringValue(4);
        if ("1".equals(encflag)) {
            String tdk = Constants.YANTAI_TDKKEY;
            int lenr = 8 - bodylen % 8;
            byte[] head = new byte[hlen];
            byte[] decdata = new byte[bodylen + lenr];
            System.arraycopy(data, 0, head, 0, hlen);
            System.arraycopy(data, hlen, decdata, 0, bodylen);
            byte[] encdata = DES3.des3Packet(decdata, tdk.getBytes());
            send = new byte[hlen + encdata.length];
            System.arraycopy(head, 0, send, 0, hlen);
            System.arraycopy(encdata, 0, send, hlen, encdata.length);

        } else {
            send = data;
        }

        CommAdapter adapter = new CommAdapter(Constants.IP, 3551);
        adapter.setHeadlen(4); // 长度头：4字节
        byte[] recv = adapter.doComm(send);

        byte[] recv2 = null;
        byte[] b = new byte[1];
        System.arraycopy(recv, 11, b, 0, 1);
        String rspenc = new String(b);
        if ("1".equals(rspenc)) {
            String tdk = Constants.YANTAI_TDKKEY;
            byte[] h7 = new byte[4];
            System.arraycopy(recv, 28, h7, 0, 4);
            int orilen = Integer.parseInt(new String(h7));
            int enclen = recv.length - Constants.ATMP_HEADER_LENGTH;
            byte[] head = new byte[Constants.ATMP_HEADER_LENGTH];
            byte[] encdata = new byte[enclen];
            System.arraycopy(recv, 0, head, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(recv, Constants.ATMP_HEADER_LENGTH, encdata, 0, enclen);
            byte[] decdata = DES3.undes3Packet(encdata, tdk.getBytes());

            recv2 = new byte[Constants.ATMP_HEADER_LENGTH + orilen];
            System.arraycopy(head, 0, recv2, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(decdata, 0, recv2, Constants.ATMP_HEADER_LENGTH, orilen);
        } else {
            recv2 = recv;
        }

        IsoMessage rsp = null;
        MessageFactory<IsoMessage> fac = new MessageFactory<IsoMessage>();
        try {
            rsp = fac.parseMessage(recv2, 32);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String respcode = rsp.getStringValue(39);
        if ("00".equals(respcode)) {
            is_work = true;
            // 芯片卡，终端需要做ARPC验证
            if (rsp.getField(55) != null) {
                // ARPC验证
            }

            String path = "/sdcard/Test/";
            String strFile = path + "0001" + Constants.YANTAI_TERMNO + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE) + ".txt";
//            mkdirs(strFile);
//
                        Logger.e(strFile);
            File f = new File(strFile);
            if (!f.exists()) {
                Logger.e("无文件");
                //当天第一次签到，未创建文件夹,创建文件

                f.mkdirs();

            } else {
                mkdirs(strFile);
                Logger.e("有文件");
//                已有文件
            }


            inter.unpackReSpone(rsp, getApplicationContext());
            Intent intent;
            intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
            mTimer2.cancel();
            mTask2.cancel();
            this.finish();
        } else {
            Logger.e("交易失败:[{}]-[{}]" + respcode + rsp.getStringValue(40));
        }
        if (!is_work && timer_time > 5000) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LogingActivity.this, "网络连接异常，请检查您的网络！", Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    /**
     * 创建文件夹
     *
     * @param path
     */
    public void mkdirs(String path) {
        Logger.e(path);


            Logger.d("有文件");
//            Logger.e(loadFromSDFile(path));
            if (loadFromSDFile(path) == null) {
                Logger.d("无数据");
            } else {
                //上传流水
                SFTPUtils sftpUtils = new SFTPUtils("172.32.25.234", "user", "user");

                sftpUtils.connect();
                Logger.d("连接成功");
                Logger.e("remotepath"+"/home/icyp/user/today/" + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE));
                Logger.e("remotename"+"0001" + Constants.YANTAI_TERMNO + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE) + ".txt");
                Logger.e("localpath"+Environment.getExternalStorageDirectory().getPath() + "//sdcard/Test/");
                Logger.e("locationname"+"//sdcard/Test/"+ "0001" + Constants.YANTAI_TERMNO + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE) + ".txt");
                sftpUtils.uploadFile("/home/user/today/" + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE),
                        "0001" + Constants.YANTAI_TERMNO + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE) + ".txt",
                        Environment.getExternalStorageDirectory().getPath() + "//sdcard/Test/",
                        "0001" + Constants.YANTAI_TERMNO + DateUtil.getCurrentTime(DateUtil.NOMAL_DATE) + ".txt");


                Logger.d("上传成功");
                sftpUtils.disconnect();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "流水上传成功", Toast.LENGTH_SHORT).show();
                    }
                });

            }


    }

    private String loadFromSDFile(String fname) {

        Logger.e(fname);
        String result = null;
        try {
            Logger.e(Environment.getExternalStorageDirectory().getPath() + fname);
            File f = new File(Environment.getExternalStorageDirectory().getPath() + fname);
            int length = (int) f.length();
            byte[] buff = new byte[length];
            FileInputStream fin = new FileInputStream(f);
            fin.read(buff);
            fin.close();
            result = new String(buff, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();

        }
        return result;
    }


    /**
     * 获取主秘钥
     *
     * @param transn
     */
    public static void excuteMain(String transn) {
        IsoMessage msg = null;
        RTKInterface inter = new RTKInterface();

        msg = inter.packRequest(transn);
        byte[] data = msg.writeData();
        // 重写报文头第7域长度值
        int hlen = Constants.ATMP_HEADER_LENGTH;
        int bodylen = data.length - hlen;
        String headF7 = ServiceCommon.appendZero(bodylen, 4);
        System.arraycopy(headF7.getBytes(), 0, data, 28, 4);
        // 生成MAC
        if (msg.getField(128) != null) {
            int start = hlen;
            int length = data.length - start - 8;
            byte[] inmac = new byte[length];
            byte[] outmac = new byte[16];
            System.arraycopy(data, start, inmac, 0, length);
            Logger.e("MAC数据=[{}]" + HexT.byteArr2HexStr(inmac));
            String mackey = Constants.YANTAI_MACKEY;
            // MAC99算法mak只需要16字节密钥
            if (mackey.length() > 16) {
                mackey = mackey.substring(0, 16);
            }
            DES3.getMacBlock_99(inmac, mackey.getBytes(), outmac);
            System.arraycopy(outmac, 0, data, data.length - 8, 8);
            Logger.e("请求MAC=[{}]" + new String(outmac).substring(0, 8));
        }
        byte[] send = null;
        // 报文加密，公网传输时，业务交易必须报文加密
        String encflag = msg.getHeadStringValue(4);
        if ("1".equals(encflag)) {
            String tdk = Constants.YANTAI_TDKKEY;
            int lenr = 8 - bodylen % 8;
            byte[] head = new byte[hlen];
            byte[] decdata = new byte[bodylen + lenr];
            System.arraycopy(data, 0, head, 0, hlen);
            System.arraycopy(data, hlen, decdata, 0, bodylen);
            byte[] encdata = DES3.des3Packet(decdata, tdk.getBytes());
            send = new byte[hlen + encdata.length];
            System.arraycopy(head, 0, send, 0, hlen);
            System.arraycopy(encdata, 0, send, hlen, encdata.length);

        } else {
            send = data;
        }

        CommAdapter adapter = new CommAdapter(Constants.IP, 3551);
        adapter.setHeadlen(4); // 长度头：4字节
        byte[] recv = adapter.doComm(send);

        byte[] recv2 = null;
        byte[] b = new byte[1];
        System.arraycopy(recv, 11, b, 0, 1);
        String rspenc = new String(b);
        if ("1".equals(rspenc)) {
            String tdk = Constants.YANTAI_TDKKEY;
            byte[] h7 = new byte[4];
            System.arraycopy(recv, 28, h7, 0, 4);
            int orilen = Integer.parseInt(new String(h7));
            int enclen = recv.length - Constants.ATMP_HEADER_LENGTH;
            byte[] head = new byte[Constants.ATMP_HEADER_LENGTH];
            byte[] encdata = new byte[enclen];
            System.arraycopy(recv, 0, head, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(recv, Constants.ATMP_HEADER_LENGTH, encdata, 0, enclen);
            byte[] decdata = DES3.undes3Packet(encdata, tdk.getBytes());

            recv2 = new byte[Constants.ATMP_HEADER_LENGTH + orilen];
            System.arraycopy(head, 0, recv2, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(decdata, 0, recv2, Constants.ATMP_HEADER_LENGTH, orilen);
        } else {
            recv2 = recv;
        }

        IsoMessage rsp = null;
        MessageFactory<IsoMessage> fac = new MessageFactory<IsoMessage>();
        try {
            rsp = fac.parseMessage(recv2, 32);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String respcode = rsp.getStringValue(39);
        if ("00".equals(respcode)) {
            // 芯片卡，终端需要做ARPC验证
            if (rsp.getField(55) != null) {
                // ARPC验证
            }
            inter.unpackReSpone(rsp);
        } else {
            Logger.e("交易失败:[{}]-[{}]" + respcode + rsp.getStringValue(40));
        }

    }
}
